package com.ruoyi.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.project.domain.entity.PhaseDictionary;
import com.ruoyi.project.domain.entity.ProjectPay;
import com.ruoyi.project.domain.entity.ProjectWarranty;
import com.ruoyi.project.domain.query.ProjectPayQuery;
import com.ruoyi.project.domain.query.ProjectWarrantyQuery;
import com.ruoyi.project.mapper.ProjectPayMapper;
import com.ruoyi.project.mapper.ProjectWarrantyMapper;
import com.ruoyi.project.service.IPhaseDictionaryService;
import com.ruoyi.project.service.IProjectPayService;
import com.ruoyi.project.service.IProjectWarrantyService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


@Service
public class ProjectWarrantyServiceImpl extends ServiceImpl<ProjectWarrantyMapper, ProjectWarranty> implements IProjectWarrantyService {

    @Resource
    private ProjectWarrantyMapper projectWarrantyMapper;


    @Resource
    private IPhaseDictionaryService dictionaryService;

    //新增
    @Override
    public Boolean addInfo(ProjectWarranty project) throws IOException {
        project.setOperator(SecurityUtils.getLoginUser().getUser().getNickName());
        if (project.getProjectNo().contains("XS")){
            //检查有无已经生成的
            LambdaQueryWrapper<ProjectWarranty> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProjectWarranty::getProjectNo, project.getProjectNo());
            projectWarrantyMapper.delete(queryWrapper);
            return this.save(project);
        }
        setFileName(project);
        Long phaseId = project.getPhaseId();

        if (phaseId == null) {
            throw new RuntimeException("后端接口异常");
        }
        if (project.getStartDate() != null && project.getCycle() != null) {
            setEndDate(project);
        }
        PhaseDictionary byId = dictionaryService.getById(project.getPhaseId());
        project.setPhaseName(byId.getPhaseName());
        return this.save(project);
    }

    @Override
    public Boolean updateInfo(ProjectWarranty project) {
        project.setOperator(SecurityUtils.getLoginUser().getUser().getNickName());
        setFileName(project);

        if (project.getStartDate() != null && project.getCycle() != null) {
            setEndDate(project);
        }

        return this.updateById(project);
    }

    @Override
    public Boolean deleteInfo(String id) {
        return this.removeById(id);
    }

    @Override
    public ProjectWarranty getInfoById(String id) {
        return this.getById(id);
    }

    @Override
    public List<ProjectWarranty> getList(ProjectWarrantyQuery query) {
        LambdaQueryWrapper<ProjectWarranty> wrapper = new QueryWrapper<ProjectWarranty>().lambda()
                .eq(query.getProjectNo() != null, ProjectWarranty::getProjectNo, query.getProjectNo());
        return this.list(wrapper);
    }

    public void setFileName(ProjectWarranty project) {
        String filePaths = project.getFiles();
        // 按逗号分隔字符串
        String fileName = "";
        try {
            if (StringUtils.isNotEmpty(filePaths) && filePaths.contains(",")) {
                String[] paths = filePaths.split(",");
                // 遍历每个路径并提取基础文件名
                String[] baseFileNames = new String[paths.length];
                for (int i = 0; i < paths.length; i++) {
                    String pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getUploadPath(), paths[i]);
                    String name = FileUtils.getName(pathFileName);
                    // 去掉时间戳部分（假设文件名与时间戳之间用"_"分隔）
                    String nameSuffix = name.lastIndexOf("_") != -1 ? name.substring(0, name.lastIndexOf("_")) : name;
                    // 提取文件扩展名
                    String extend = "";
                    if (name != null && name.contains(".")) {
                        extend = name.substring(name.lastIndexOf("."));
                    }
                    fileName = fileName + nameSuffix + extend + ",";
                }

            } else {
                if (StringUtils.isNotEmpty(filePaths)) {
                    String pathFileName = null;

                    pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getUploadPath(), filePaths);
                    String name = FileUtils.getName(pathFileName);
                    // 去掉时间戳部分（假设文件名与时间戳之间用"_"分隔）
                    String nameSuffix = name.lastIndexOf("_") != -1 ? name.substring(0, name.lastIndexOf("_")) : name;
                    // 提取文件扩展名
                    String extend = "";
                    if (name != null && name.contains(".")) {
                        extend = name.substring(name.lastIndexOf("."));
                    }
                    fileName = fileName + nameSuffix + extend + ",";
                }
                String pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getUploadPath(), filePaths);
                System.out.println("pathFileName:" + pathFileName);
            }
        } catch (IOException e) {
            throw new RuntimeException("文件保存失败,请检查规范文件名称");
        }
        if (StringUtils.isNotEmpty(fileName)) {
            project.setFileName(fileName.substring(0, fileName.length() - 1));
        } else {
            project.setFileName("");
        }

    }


    public void setEndDate(ProjectWarranty project) {
        Date startDate = project.getStartDate();

// 周期（单位为月），例如：12 个月
        Double cycle = project.getCycle();
        long monthsToAdd = Math.round(cycle); // 如果是浮点数，建议四舍五入

        // 将 Date 转换为 LocalDate
        LocalDate localStartDate = startDate.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        // 精确加上几个月（保留具体日期，比如 8 月 1 日 + 12 个月 = 次年 8 月 1 日）
        LocalDate endDate = localStartDate.plusMonths(monthsToAdd);

        // 转换回 Date 类型用于设置
        Date endDateAsDate = Date.from(endDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

        // 设置截止日期
        project.setEndDate(endDateAsDate);

    }

}
